package com.aliyun.oss.internal;

import com.aliyun.oss.common.utils.HttpUtil;

import java.net.URI;

import static com.aliyun.oss.internal.OSSConstants.DEFAULT_CHARSET_NAME;

public class OSSUtils {

    public static String determineResourcePath(String bucket, String key) {
        return urlEncodeKey(key);
    }


    private static String buildCanonicalHost(URI endpoint) {
        return endpoint.getHost();
    }

    /**
     * Encode object URI.
     */
    private static String urlEncodeKey(String key) {
        if (key.startsWith("/")) {
            return HttpUtil.urlEncode(key, DEFAULT_CHARSET_NAME);
        }

        StringBuffer resultUri = new StringBuffer();

        String[] keys = key.split("/");
        resultUri.append(HttpUtil.urlEncode(keys[0], DEFAULT_CHARSET_NAME));
        for (int i = 1; i < keys.length; i++) {
            resultUri.append("/").append(HttpUtil.urlEncode(keys[i], DEFAULT_CHARSET_NAME));
        }

        if (key.endsWith("/")) {
            // String#split ignores trailing empty strings,
            // e.g., "a/b/" will be split as a 2-entries array,
            // so we have to append all the trailing slash to the uri.
            for (int i = key.length() - 1; i >= 0; i--) {
                if (key.charAt(i) == '/') {
                    resultUri.append("/");
                } else {
                    break;
                }
            }
        }

        return resultUri.toString();
    }

}
